import { Request, Response, NextFunction } from "express";
import { ZodSchema } from "zod";
import { HttpError } from "../utils/httpError";
import { ErrorCode } from "../constants/errorCode";

export const validate = (schema: ZodSchema<any>) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      const formatted = result.error.format();
      const messages = Object.entries(formatted)
        .filter(([key]) => key !== "_errors")
        .map(
          ([key, val]) => `${key}: ${(val as any)._errors?.[0] || "Invalid"}`
        );

      return next(
        new HttpError(ErrorCode.VALIDATION, 400, messages.join(", "))
      );
    }

    req.body = result.data;
    next();
  };
};
